/**
 * Created by XHL on 2022-07-26.
 */

#include <conio.h>
#include <Game.h>

namespace entity {
	Game::Game(PInfo &info_a, PInfo &info_b) {
		this->m_pa = new Tank(info_a);
		this->m_pb = new Tank(info_b);
		this->m_map = new TheMap(0, 20);
		this->run_flag = true;
		this->associate();
	}

	void Game::response() {
		if (this->m_pa->get_hp() <= 0 ||
			this->m_pb->get_hp() <= 0 ||
			this->m_map->get_size() <= 2) {
			this->game_over();
		}
	}

	void Game::associate() {
		this->m_pa->set_game(this);
		this->m_pb->set_game(this);

		this->m_pa->set_opponent(this->m_pb);
		this->m_pb->set_opponent(this->m_pa);

		this->m_pa->set_map(this->m_map);
		this->m_pb->set_map(this->m_map);

		this->m_map->set_player_A(this->m_pa);
		this->m_map->set_player_B(this->m_pb);
	}

	void Game::game_over() {
		int a_hp = this->m_pa->get_hp();
		int b_hp = this->m_pb->get_hp();
		if (a_hp == b_hp) {
			entity::Game::display("  TIE ");
		}
		if (a_hp > b_hp) {
			entity::Game::display("A Wins");
		}
		if (a_hp < b_hp) {
			entity::Game::display("B Wins");
		}
		this->run_flag = false;
	}

	void Game::start() {
		while (this->run_flag) {
			if (!_kbhit()) continue;
			int key = _getch();
			this->run_flag = key != 27;
			if (this->m_pa->is_movable()) {
				this->m_pa->try_to_move(key);
				this->m_pb->set_movable(!this->m_pa->is_movable());
			} else {
				this->m_pb->try_to_move(key);
				this->m_pa->set_movable(!this->m_pb->is_movable());
			}
		}
	}

	void Game::display(const char *message) {
		handle::set_cursor_location({ 20, 10 });
		std::cout << "\033[43m\033[26X";
		handle::set_cursor_location({ 20, 11 });
		std::cout << "\033[43m\033[26X";
		handle::set_cursor_location({ 20, 12 });
		std::cout << "\033[43m          " << message << "\033[43m          \033[0m";
		handle::set_cursor_location({ 20, 13 });
		std::cout << "\033[43m\033[26X";
		handle::set_cursor_location({ 20, 14 });
		std::cout << "\033[43m\033[26X";
	}
} // entity